<template>
   <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
    >
   <van-icon slot="left" name="arrow-left"  @click="$router.back()"/>
    </van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="isLoading">
        <van-loading
          color="#3296fa"
          vertical
        >加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-else-if="artices.title" >
        <!-- 文章标题 -->
        <h1 class="article-title">{{artices.title}}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="artices.aut_photo"
          />
          <div slot="title" class="user-name">{{artices.aut_name}}</div>
          <div slot="label" class="publish-date">{{artices.pubdate | relativeTime}}</div>
          <!-- 1.绑定点击事件：
          2.如果已关注，将按钮变为未关注，
          3.未关注，判断是否关注是自己 -->
           <van-button
            class="follow-btn"
            round
            size="small"
            v-if="artices.is_followed"
            @click="onFollow()"
          >已关注</van-button>
          <van-button
            class="follow-btn"
            type="info"
            color="#3296fa"
            round
            size="small"
            icon="plus"
            v-else
            @click="onFollow()"
          >关注</van-button>
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div class="article-content markdown-body" v-html="artices.content"></div>
        <van-divider>正文结束</van-divider>
        <!-- 评论 -->

        <!-- 评论列表使用组件 -->
        <CommentList
        :source="artices.art_id"
        :list = 'commentList'
        @onload-success ='totalCommentCount = $event'
        ref="commentList"
        @reply_click = 'onReplyShow'
        > <!-- $event相当于子组件传递过来的此参数 -->
        </CommentList>
        <!-- 评论列表组件 -->

         <!-- 底部区域 -->
          <div class="article-bottom">
            <van-button
              class="comment-btn"
              type="default"
              round
              size="small"
              @click="isPostShow = true"
            >写评论</van-button>
            <van-icon
              name="comment-o"
              :info="totalCommentCount"
              color="#777"
              @click="isreplyShow=true"
            />
            <!-- //收藏 -->
            <CollectArticle v-model="artices" ></CollectArticle>
            <!-- 点赞 -->
            <Attitude v-model="artices.attitude"></Attitude>
            <van-icon name="share" color="#777777"></van-icon>
          </div>
          <!-- /底部区域 -->

          <!-- 发布评论 -->
          <van-popup v-model="isPostShow" position="bottom">
            <!-- //评论弹层组件 -->
            <commentPost
            :target ='artices.art_id'
            @post-success='onPonstSuccess'
            ></commentPost>
            <!-- //评论弹层组件 -->
          </van-popup>
          <!-- 发布评论 -->
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-else-if="errStatus==404">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-else>
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="locagetArticleById()">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>
     <!-- 发布评论的评论弹层 -->
      <van-popup v-model="isreplyShow" position="bottom"
      :style="{height:'100%'}">
          <commentReplay
          :comment ='commentitem'
          :isreplyShow='isreplyShow'
          @onisreplyShow='onisreplyShow'
          />
      </van-popup>
     <!-- 发布评论的评论弹层 -->

  </div>
</template>

<script>
import commentReplay from './commponents/comment-replay.vue'
import commentPost from './commponents/comment-post.vue'
import CommentList from '@/views/article/commponents/comment-list.vue'
import Attitude from '@/components/like-article'
import CollectArticle from '@/components/collect-article'
import { addFollow, deleteFollow } from '@/api/user'
import './github-markdown.css'
import { getArticleById } from '@/api/acticle'
import { ImagePreview } from 'vant'

export default {
  name: 'ArticleIndex',
  created () {
    this.locagetArticleById()
    // console.log(this.artices)
  },
  mounted () {

  },
  props: {
    articleId: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      isreplyShow: false, // 评论回复弹窗
      isPostShow: false, // 发布文章评论弹层
      artices: {},
      isLoading: true, // 加载中条件
      errStatus: 0, // 失败的状态码
      totalCommentCount: 0, // 评论总数
      commentList: [],
      commentitem: {} // 当前评论项
    }
  },
  methods: {
    // 请求文章详情
    async locagetArticleById () {
      this.isLoading = true // 默认请求一开始打开loading
      try {
        // 模拟报错
        // if (Math.random() > 0.5) {
        //   // 报错
        //   JSON.parse('111fsfsf')
        // }
        const { data } = await getArticleById(this.articleId)
        // console.log(data)
        this.artices = data.data
        this.isLoading = false // 关闭加载状态
        // 数据更新是同步的，页面渲染是异步的
        // 1.获取文章区域所有图片
        // 2.依次绑定点击事件
        // 2.每张图片的点击执行预览
        setTimeout(() => {
          // 获取所有img
          const imgs = [...document.querySelectorAll('.article-content img')]
          // DOM元素是 数据渲染出来的 需要进行异步获取
          // console.log(imgs)

          imgs.forEach((item, index) => {
            item.onclick = () => {
              ImagePreview({
                images: imgs.map(item => item.src),
                startPosition: index
              })
            }
          })
        }, 0)
      } catch (err) {
        // console.log(err)
        this.isLoading = false // 关闭加载状态
        // 如果加载错误为404
        // 如果有err.response，并且有status属性为404
        if (err.response?.status === 404) {
          this.errStatus = 404
        }
      }
    },
    // 关注操作
    async onFollow () {
      try {
        // 如果已关注，取消
        if (this.artices.is_followed) {
          await deleteFollow(this.artices.aut_id)
        } else {
        // 如果未关注，关注
          await addFollow(this.artices.aut_id)
        }
        this.artices.is_followed = !this.artices.is_followed
      } catch (err) {
        // 关注自己会报错，需要捕获错误，判断是否为400
        if (err.response && err.response.status === 400) {
          this.$toast('用户不能关注自己')
        } else {
          this.$toast('操作失败，稍后重试')
        }
      }
    },
    // 发布评论组件内的操作
    onPonstSuccess (data) {
    //   // 关闭弹层
      this.isPostShow = false
      //   // 将发布的评论添加键评论项内
      // 兄弟组件通信
      // 将list定义在父组件内
      // 方法一
      // 父组件给子组件传值，进行共享
      this.commentList.unshift(data)
      // 方法二
      // 给组件设置ref名，就可以通过this.$refs获取子组件的实例对象，利用实例对象的属性，就可以操作子组件的数据
      // this.$refs.commentList.list.unshift(data)
      this.totalCommentCount++
    },
    // 评论回复
    onReplyShow (comment) {
      this.isreplyShow = true
      this.commentitem = comment
    },
    // 关闭弹窗
    onisreplyShow () {
      this.isreplyShow = false
    }
  },
  // 注册组件
  components: {
    CollectArticle, // 收藏
    Attitude, // 点赞
    CommentList, // 评论组件
    commentPost, // 添加评论
    commentReplay // 回复弹窗
  }
}
</script>

<style scoped lang="less">
.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
  /deep/.van-nav-bar .van-icon{
    color: #fff;
  }
}
</style>
